package com.restphp.java.hashdb.dcs.utils;

import com.restphp.java.hashdb.dcs.constant.IPType;
import com.restphp.java.hashdb.dcs.po.ClusterNode;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;

/**
 * 服务器节点工具.
 * Created by sofical on 2020/8/11.
 */
public class ClusterNodeUtils {
    /**
     * 获取节点服务器的IP地址.
     * @param node 群集节点.
     * @return ip地址.
     */
    public static String getHostAddress(ClusterNode node) {
        try {
            InetAddress inetAddress;
            if (IPType.IPV4.equals(node.getIpType())) {
                inetAddress = Inet4Address.getByName(node.getAddress());
            } else {
                inetAddress = Inet6Address.getByName(node.getAddress());
            }
            return inetAddress.getHostAddress();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 是否为本机地址.
     * @param ip ip.
     * @param ipType ip类型.
     * @return 绑定结果.
     */
    public static Boolean isLocal(String ip, IPType ipType) {
        try {
            InetAddress inetAddress;
            if (IPType.IPV4.equals(ipType)) {
                inetAddress = Inet4Address.getLocalHost();
            } else {
                inetAddress = Inet6Address.getLocalHost();
            }
            return ip.equals(inetAddress.getHostAddress());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*public static void main(String[] args) {
        isLocal("127.0.0.1", IPType.IPV4);
    }*/
}
